package com.leyou.page.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @package com.leyou.page.web.service
 * @description: 页面渲染的业务层
 * @author: 许超越
 * @date 2019/7/3 15:39
 * @version: V1.0
 */
@Service
@Slf4j
public class PageService {

    @Autowired
    private ItemClient itemClient;

    @Value("${ly.static.itemDir}")
    private String itemDir;

    @Autowired
    private SpringTemplateEngine templateEngine;

    /**
     * 查询模板需要的数据
     * @param: spuId
     * @return
     */
    public Map<String, Object> queryItemPage(Long spuId) {
        //查询spu
        SpuDTO spu = itemClient.querySpuById(spuId);
        //查询分类的集合
        List<CategoryDTO> categories = itemClient.queryCategoryByIds(spu.getCategoryIds());
        //查询品牌
        BrandDTO brand = itemClient.queryBrandById(spu.getBrandId());
        //查询规格
        List<SpecGroupDTO> specs = itemClient.querySpecsByCid(spu.getCid3());
        // 封装数据
        Map<String, Object> data = new HashMap<>();
        data.put("categories", categories);
        data.put("brand", brand);
        data.put("spuName", spu.getName());
        data.put("subTitle", spu.getSubTitle());
        data.put("skus", spu.getSkus());
        data.put("detail", spu.getSpuDetail());
        data.put("specs", specs);
        //返回数据
        return data;
    }


    /**
     * 页面静态化
     * @param: id
     */
    public void createItemHtml(Long id) {
        //准备上下文模型
        Context context = new Context();
        //将页面查询到的数据存储到上下文中
        context.setVariables(queryItemPage(id));
        //准备文件路径
        File file = new File(itemDir, id + ".html");
        try {
            //准备打印流
            PrintWriter writer = new PrintWriter(file, "UTF-8");
            //调用方法写入
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            log.error("创建静态页面失败，原因：{}", e.getMessage(), e);
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR, e);
        }
    }


    /**
     * 商品下架，删除对应的静态化商品页面
     * @param spuId
     */
    public void deleteHtml(Long spuId) {
        //创建文件对象
        File file = new File(itemDir, spuId + ".html");
        //判断文件是否存在，存在删除
        if (file.exists()) {
            if (!file.delete()) {
                log.error("静态页面删除失败，失败商品页面id为：{}", spuId);
                throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
            }
        }
    }
}
